"""
报告管理API接口
"""
from fastapi import APIRouter, Depends, HTTPException, BackgroundTasks, UploadFile, File
from fastapi.responses import FileResponse
from sqlalchemy.orm import Session
from pydantic import BaseModel, Field
from fastapi import Query
from typing import Dict, Any, List, Optional
from datetime import datetime
import os

from core.database import get_db
from core.logging_config import get_logger, log_api_request
from core.auth import get_current_active_user, require_permission
from core.exceptions import ReportError, ValidationError
from models.user import User
from models.report import ReportStatus, ReportFormat, ReportType
from services.report_service import report_service
from services.report_generation_service import report_generation_service
import models.report

# 路由器
reports_router = APIRouter(tags=["报告管理"])

# 日志记录器
logger = get_logger("reports_api")


class ReportCreateRequest(BaseModel):
    """创建报告请求"""
    title: str = Field(..., min_length=1, max_length=500, description="报告标题")
    description: Optional[str] = Field(None, description="报告描述")
    report_type: str = Field(..., description="报告类型")
    format: str = Field(..., description="报告格式")
    template_id: Optional[int] = Field(None, description="模板ID")
    start_date: Optional[datetime] = Field(None, description="开始日期")
    end_date: Optional[datetime] = Field(None, description="结束日期")
    data_source_ids: Optional[List[int]] = Field(None, description="数据源ID列表")
    task_ids: Optional[List[int]] = Field(None, description="任务ID列表")
    region_filter: Optional[Dict[str, Any]] = Field(None, description="区域过滤器")
    pollution_type_filter: Optional[Dict[str, Any]] = Field(None, description="污染类型过滤器")
    config: Optional[Dict[str, Any]] = Field(None, description="报告配置")
    ai_prompt: Optional[str] = Field(None, description="AI提示词")


class ReportUpdateRequest(BaseModel):
    """更新报告请求"""
    title: Optional[str] = Field(None, min_length=1, max_length=500, description="报告标题")
    description: Optional[str] = Field(None, description="报告描述")
    start_date: Optional[datetime] = Field(None, description="开始日期")
    end_date: Optional[datetime] = Field(None, description="结束日期")
    data_source_ids: Optional[List[int]] = Field(None, description="数据源ID列表")
    task_ids: Optional[List[int]] = Field(None, description="任务ID列表")
    region_filter: Optional[Dict[str, Any]] = Field(None, description="区域过滤器")
    pollution_type_filter: Optional[Dict[str, Any]] = Field(None, description="污染类型过滤器")
    config: Optional[Dict[str, Any]] = Field(None, description="报告配置")
    ai_prompt: Optional[str] = Field(None, description="AI提示词")


class TemplateCreateRequest(BaseModel):
    """创建模板请求"""
    name: str = Field(..., min_length=1, max_length=200, description="模板名称")
    description: Optional[str] = Field(None, description="模板描述")
    report_type: str = Field(..., description="报告类型")
    format: str = Field(..., description="报告格式")
    category: Optional[str] = Field(None, description="模板分类")
    template_content: Optional[str] = Field(None, description="模板内容")
    template_config: Optional[Dict[str, Any]] = Field(None, description="模板配置")
    field_mapping: Optional[Dict[str, Any]] = Field(None, description="字段映射")
    ai_prompt_template: Optional[str] = Field(None, description="AI提示词模板")
    ai_model_config: Optional[Dict[str, Any]] = Field(None, description="AI模型配置")
    style_config: Optional[Dict[str, Any]] = Field(None, description="样式配置")
    chart_config: Optional[Dict[str, Any]] = Field(None, description="图表配置")
    sort_order: Optional[int] = Field(0, description="排序顺序")


class TemplateUpdateRequest(BaseModel):
    """更新模板请求"""
    name: Optional[str] = Field(None, min_length=1, max_length=200, description="模板名称")
    description: Optional[str] = Field(None, description="模板描述")
    report_type: Optional[str] = Field(None, description="报告类型")
    format: Optional[str] = Field(None, description="报告格式")
    category: Optional[str] = Field(None, description="模板分类")
    template_content: Optional[str] = Field(None, description="模板内容")
    template_config: Optional[Dict[str, Any]] = Field(None, description="模板配置")
    field_mapping: Optional[Dict[str, Any]] = Field(None, description="字段映射")
    ai_prompt_template: Optional[str] = Field(None, description="AI提示词模板")
    ai_model_config: Optional[Dict[str, Any]] = Field(None, description="AI模型配置")
    style_config: Optional[Dict[str, Any]] = Field(None, description="样式配置")
    chart_config: Optional[Dict[str, Any]] = Field(None, description="图表配置")
    sort_order: Optional[int] = Field(None, description="排序顺序")


class ReportResponse(BaseModel):
    """报告响应"""
    id: int
    title: str
    description: Optional[str]
    report_type: str
    format: str
    status: str
    start_date: Optional[datetime]
    end_date: Optional[datetime]
    data_source_ids: Optional[List[int]]
    task_ids: Optional[List[int]]
    template_id: Optional[int]
    config: Optional[Dict[str, Any]]
    file_path: Optional[str]
    file_name: Optional[str]
    file_size: Optional[int]
    generation_time: Optional[float]
    page_count: Optional[int]
    chart_count: int
    published_at: Optional[datetime]
    creator_id: int
    created_at: datetime
    updated_at: datetime
    
    class Config:
        from_attributes = True


class TemplateResponse(BaseModel):
    """模板响应"""
    id: int
    name: str
    description: Optional[str]
    report_type: str
    format: str
    category: Optional[str]
    template_content: Optional[str]
    template_config: Optional[Dict[str, Any]]
    field_mapping: Optional[Dict[str, Any]]
    ai_prompt_template: Optional[str]
    ai_model_config: Optional[Dict[str, Any]]
    style_config: Optional[Dict[str, Any]]
    chart_config: Optional[Dict[str, Any]]
    usage_count: int
    last_used: Optional[datetime]
    creator_id: int
    is_system: bool
    sort_order: int
    created_at: datetime
    updated_at: datetime
    
    class Config:
        from_attributes = True


class ReportListResponse(BaseModel):
    """报告列表响应"""
    total: int
    page: int
    page_size: int
    items: List[ReportResponse]


class TemplateListResponse(BaseModel):
    """模板列表响应"""
    total: int
    page: int
    page_size: int
    items: List[TemplateResponse]


class DailyReportRequest(BaseModel):
    """日报生成请求"""
    report_date: Optional[datetime] = Field(None, description="报告日期，默认为今天")


class WeeklyReportRequest(BaseModel):
    """周报生成请求"""
    week_start: Optional[datetime] = Field(None, description="周开始日期，默认为本周一")


class MonthlyReportRequest(BaseModel):
    """月报生成请求"""
    year: Optional[int] = Field(None, description="年份，默认为今年")
    month: Optional[int] = Field(None, ge=1, le=12, description="月份，默认为本月")


class CustomReportRequest(BaseModel):
    """自定义报告生成请求"""
    title: str = Field(..., description="报告标题")
    start_date: datetime = Field(..., description="开始日期")
    end_date: datetime = Field(..., description="结束日期")
    sections: List[str] = Field(
        ["overview", "trends", "geo_analysis", "category_analysis", "key_issues"],
        description="包含的章节"
    )
    analysis_config: Optional[Dict[str, Any]] = Field(None, description="分析配置")


# 报告管理接口
@reports_router.get("/", response_model=ReportListResponse)
@log_api_request("list_reports")
@require_permission("report:view")
async def list_reports(
    status: Optional[str] = Query(None, description="报告状态过滤"),
    report_type: Optional[str] = Query(None, description="报告类型过滤"),
    format: Optional[str] = Query(None, description="报告格式过滤"),
    page: int = Query(1, ge=1, description="页码"),
    page_size: int = Query(20, ge=1, le=100, description="每页数量"),
    current_user: User = Depends(get_current_active_user),
    db: Session = Depends(get_db)
):
    """获取报告列表"""
    logger.info("获取报告列表请求")
    
    try:
        filters = {}
        if status:
            filters["status"] = status
        if report_type:
            filters["report_type"] = report_type
        if format:
            filters["format"] = format
        
        result = report_service.list_reports(db, filters, page, page_size)
        
        return ReportListResponse(
            total=result["total"],
            page=result["page"],
            page_size=result["page_size"],
            items=result["items"]
        )
        
    except Exception as e:
        logger.error(f"获取报告列表失败: {str(e)}")
        raise HTTPException(status_code=500, detail=str(e))


@reports_router.post("/", response_model=ReportResponse)
@log_api_request("create_report")
@require_permission("report:create")
async def create_report(
    request: ReportCreateRequest,
    current_user: User = Depends(get_current_active_user),
    db: Session = Depends(get_db)
):
    """创建报告"""
    logger.info(f"创建报告请求: {request.title}")
    
    try:
        # 验证报告类型
        if request.report_type not in [t.value for t in ReportType]:
            raise HTTPException(status_code=400, detail=f"不支持的报告类型: {request.report_type}")
        
        # 验证报告格式
        if request.format not in [f.value for f in ReportFormat]:
            raise HTTPException(status_code=400, detail=f"不支持的报告格式: {request.format}")
        
        # 转换请求数据
        report_data = {
            "title": request.title,
            "description": request.description,
            "report_type": request.report_type,
            "format": request.format,
            "template_id": request.template_id,
            "start_date": request.start_date,
            "end_date": request.end_date,
            "data_source_ids": request.data_source_ids,
            "task_ids": request.task_ids,
            "region_filter": request.region_filter,
            "pollution_type_filter": request.pollution_type_filter,
            "config": request.config,
            "ai_prompt": request.ai_prompt
        }
        
        # 创建报告
        report = await report_service.create_report(report_data, current_user.id, db)
        
        return ReportResponse.from_orm(report)
        
    except HTTPException:
        raise
    except Exception as e:
        logger.error(f"创建报告失败: {str(e)}")
        raise HTTPException(status_code=500, detail=str(e))


@reports_router.get("/{report_id}", response_model=ReportResponse)
@log_api_request("get_report")
@require_permission("report:view")
async def get_report(
    report_id: int,
    current_user: User = Depends(get_current_active_user),
    db: Session = Depends(get_db)
):
    """获取报告详情"""
    logger.info(f"获取报告详情请求: {report_id}")
    
    try:
        report = report_service.get_report(db, report_id)
        
        if not report:
            raise HTTPException(status_code=404, detail="报告不存在")
        
        return ReportResponse.from_orm(report)
        
    except HTTPException:
        raise
    except Exception as e:
        logger.error(f"获取报告详情失败: {str(e)}")
        raise HTTPException(status_code=500, detail=str(e))


@reports_router.put("/{report_id}", response_model=ReportResponse)
@log_api_request("update_report")
@require_permission("report:edit")
async def update_report(
    report_id: int,
    request: ReportUpdateRequest,
    current_user: User = Depends(get_current_active_user),
    db: Session = Depends(get_db)
):
    """更新报告"""
    logger.info(f"更新报告请求: {report_id}")
    
    try:
        # 获取报告
        report = db.query(models.report.Report).filter(models.report.Report.id == report_id).first()
        if not report:
            raise HTTPException(status_code=404, detail="报告不存在")
        
        # 只能更新待执行或生成失败的任务
        if report.status not in [ReportStatus.PENDING, ReportStatus.FAILED]:
            raise HTTPException(status_code=400, detail="只能更新待生成或生成失败的任务")
        
        # 更新字段
        if request.title is not None:
            report.title = request.title
        if request.description is not None:
            report.description = request.description
        if request.start_date is not None:
            report.start_date = request.start_date
        if request.end_date is not None:
            report.end_date = request.end_date
        if request.data_source_ids is not None:
            report.data_source_ids = request.data_source_ids
        if request.task_ids is not None:
            report.task_ids = request.task_ids
        if request.region_filter is not None:
            report.region_filter = request.region_filter
        if request.pollution_type_filter is not None:
            report.pollution_type_filter = request.pollution_type_filter
        if request.config is not None:
            report.config = request.config
        if request.ai_prompt is not None:
            report.ai_prompt = request.ai_prompt
        
        db.commit()
        db.refresh(report)
        
        return ReportResponse.from_orm(report)
        
    except HTTPException:
        raise
    except Exception as e:
        logger.error(f"更新报告失败: {str(e)}")
        raise HTTPException(status_code=500, detail=str(e))


@reports_router.delete("/{report_id}")
@log_api_request("delete_report")
@require_permission("report:delete")
async def delete_report(
    report_id: int,
    current_user: User = Depends(get_current_active_user),
    db: Session = Depends(get_db)
):
    """删除报告"""
    logger.info(f"删除报告请求: {report_id}")
    
    try:
        success = report_service.delete_report(db, report_id)
        
        if not success:
            raise HTTPException(status_code=404, detail="报告不存在")
        
        return {"message": "报告删除成功"}
        
    except HTTPException:
        raise
    except Exception as e:
        logger.error(f"删除报告失败: {str(e)}")
        raise HTTPException(status_code=500, detail=str(e))


@reports_router.post("/{report_id}/generate")
@log_api_request("generate_report")
@require_permission("report:execute")
async def generate_report(
    report_id: int,
    background_tasks: BackgroundTasks,
    current_user: User = Depends(get_current_active_user),
    db: Session = Depends(get_db)
):
    """生成报告"""
    logger.info(f"生成报告请求: {report_id}")
    
    try:
        # 获取报告
        report = report_service.get_report(db, report_id)
        if not report:
            raise HTTPException(status_code=404, detail="报告不存在")
        
        # 检查报告状态
        if report.status == ReportStatus.GENERATING:
            raise HTTPException(status_code=400, detail="报告正在生成中")
        
        # 在后台任务中生成报告
        background_tasks.add_task(report_service.generate_report, db, report_id)
        
        return {"message": "报告生成任务已启动"}
        
    except HTTPException:
        raise
    except Exception as e:
        logger.error(f"启动报告生成失败: {str(e)}")
        raise HTTPException(status_code=500, detail=str(e))


@reports_router.post("/{report_id}/publish")
@log_api_request("publish_report")
@require_permission("report:publish")
async def publish_report(
    report_id: int,
    current_user: User = Depends(get_current_active_user),
    db: Session = Depends(get_db)
):
    """发布报告"""
    logger.info(f"发布报告请求: {report_id}")
    
    try:
        success = report_service.publish_report(db, report_id, current_user.id)
        
        if not success:
            raise HTTPException(status_code=404, detail="报告不存在")
        
        return {"message": "报告发布成功"}
        
    except HTTPException:
        raise
    except Exception as e:
        logger.error(f"发布报告失败: {str(e)}")
        raise HTTPException(status_code=500, detail=str(e))


@reports_router.post("/{report_id}/archive")
@log_api_request("archive_report")
@require_permission("report:edit")
async def archive_report(
    report_id: int,
    current_user: User = Depends(get_current_active_user),
    db: Session = Depends(get_db)
):
    """归档报告"""
    logger.info(f"归档报告请求: {report_id}")
    
    try:
        success = report_service.archive_report(db, report_id)
        
        if not success:
            raise HTTPException(status_code=404, detail="报告不存在")
        
        return {"message": "报告归档成功"}
        
    except HTTPException:
        raise
    except Exception as e:
        logger.error(f"归档报告失败: {str(e)}")
        raise HTTPException(status_code=500, detail=str(e))


@reports_router.get("/{report_id}/download")
@log_api_request("download_report")
@require_permission("report:view")
async def download_report(
    report_id: int,
    current_user: User = Depends(get_current_active_user),
    db: Session = Depends(get_db)
):
    """下载报告文件"""
    logger.info(f"下载报告请求: {report_id}")
    
    try:
        file_path = report_service.get_report_file(db, report_id)
        
        if not file_path:
            raise HTTPException(status_code=404, detail="报告文件不存在")
        
        # 获取报告信息
        report = report_service.get_report(db, report_id)
        if not report:
            raise HTTPException(status_code=404, detail="报告不存在")
        
        # 返回文件
        return FileResponse(
            path=file_path,
            filename=report.file_name,
            media_type='application/octet-stream'
        )
        
    except HTTPException:
        raise
    except Exception as e:
        logger.error(f"下载报告失败: {str(e)}")
        raise HTTPException(status_code=500, detail=str(e))


# 模板管理接口
@reports_router.get("/templates/", response_model=TemplateListResponse)
@log_api_request("list_templates")
@require_permission("report:view")
async def list_templates(
    report_type: Optional[str] = Query(None, description="报告类型过滤"),
    format: Optional[str] = Query(None, description="报告格式过滤"),
    category: Optional[str] = Query(None, description="模板分类过滤"),
    is_system: Optional[bool] = Query(None, description="是否系统模板"),
    page: int = Query(1, ge=1, description="页码"),
    page_size: int = Query(20, ge=1, le=100, description="每页数量"),
    current_user: User = Depends(get_current_active_user),
    db: Session = Depends(get_db)
):
    """获取模板列表"""
    logger.info("获取模板列表请求")
    
    try:
        filters = {}
        if report_type:
            filters["report_type"] = report_type
        if format:
            filters["format"] = format
        if category:
            filters["category"] = category
        if is_system is not None:
            filters["is_system"] = is_system
        
        result = report_service.template_manager.list_templates(db, filters, page, page_size)
        
        return TemplateListResponse(
            total=result["total"],
            page=result["page"],
            page_size=result["page_size"],
            items=result["items"]
        )
        
    except Exception as e:
        logger.error(f"获取模板列表失败: {str(e)}")
        raise HTTPException(status_code=500, detail=str(e))


@reports_router.post("/templates/", response_model=TemplateResponse)
@log_api_request("create_template")
@require_permission("report:create")
async def create_template(
    request: TemplateCreateRequest,
    current_user: User = Depends(get_current_active_user),
    db: Session = Depends(get_db)
):
    """创建模板"""
    logger.info(f"创建模板请求: {request.name}")
    
    try:
        # 验证报告类型
        if request.report_type not in [t.value for t in ReportType]:
            raise HTTPException(status_code=400, detail=f"不支持的报告类型: {request.report_type}")
        
        # 验证报告格式
        if request.format not in [f.value for f in ReportFormat]:
            raise HTTPException(status_code=400, detail=f"不支持的报告格式: {request.format}")
        
        # 转换请求数据
        template_data = {
            "name": request.name,
            "description": request.description,
            "report_type": request.report_type,
            "format": request.format,
            "category": request.category,
            "template_content": request.template_content,
            "template_config": request.template_config,
            "field_mapping": request.field_mapping,
            "ai_prompt_template": request.ai_prompt_template,
            "ai_model_config": request.ai_model_config,
            "style_config": request.style_config,
            "chart_config": request.chart_config,
            "sort_order": request.sort_order
        }
        
        # 创建模板
        template = report_service.template_manager.create_template(db, template_data, current_user.id)
        
        return TemplateResponse.from_orm(template)
        
    except HTTPException:
        raise
    except Exception as e:
        logger.error(f"创建模板失败: {str(e)}")
        raise HTTPException(status_code=500, detail=str(e))


@reports_router.get("/templates/{template_id}", response_model=TemplateResponse)
@log_api_request("get_template")
@require_permission("report:view")
async def get_template(
    template_id: int,
    current_user: User = Depends(get_current_active_user),
    db: Session = Depends(get_db)
):
    """获取模板详情"""
    logger.info(f"获取模板详情请求: {template_id}")
    
    try:
        template = report_service.template_manager.get_template(db, template_id)
        
        if not template:
            raise HTTPException(status_code=404, detail="模板不存在")
        
        return TemplateResponse.from_orm(template)
        
    except HTTPException:
        raise
    except Exception as e:
        logger.error(f"获取模板详情失败: {str(e)}")
        raise HTTPException(status_code=500, detail=str(e))


@reports_router.put("/templates/{template_id}", response_model=TemplateResponse)
@log_api_request("update_template")
@require_permission("report:edit")
async def update_template(
    template_id: int,
    request: TemplateUpdateRequest,
    current_user: User = Depends(get_current_active_user),
    db: Session = Depends(get_db)
):
    """更新模板"""
    logger.info(f"更新模板请求: {template_id}")
    
    try:
        # 转换请求数据
        update_data = {
            "name": request.name,
            "description": request.description,
            "report_type": request.report_type,
            "format": request.format,
            "category": request.category,
            "template_content": request.template_content,
            "template_config": request.template_config,
            "field_mapping": request.field_mapping,
            "ai_prompt_template": request.ai_prompt_template,
            "ai_model_config": request.ai_model_config,
            "style_config": request.style_config,
            "chart_config": request.chart_config,
            "sort_order": request.sort_order
        }
        
        # 过滤None值
        update_data = {k: v for k, v in update_data.items() if v is not None}
        
        # 更新模板
        template = report_service.template_manager.update_template(db, template_id, update_data)
        
        if not template:
            raise HTTPException(status_code=404, detail="模板不存在")
        
        return TemplateResponse.from_orm(template)
        
    except HTTPException:
        raise
    except Exception as e:
        logger.error(f"更新模板失败: {str(e)}")
        raise HTTPException(status_code=500, detail=str(e))


@reports_router.delete("/templates/{template_id}")
@log_api_request("delete_template")
@require_permission("report:delete")
async def delete_template(
    template_id: int,
    current_user: User = Depends(get_current_active_user),
    db: Session = Depends(get_db)
):
    """删除模板"""
    logger.info(f"删除模板请求: {template_id}")
    
    try:
        success = report_service.template_manager.delete_template(db, template_id)
        
        if not success:
            raise HTTPException(status_code=404, detail="模板不存在")
        
        return {"message": "模板删除成功"}
        
    except HTTPException:
        raise
    except Exception as e:
        logger.error(f"删除模板失败: {str(e)}")
        raise HTTPException(status_code=500, detail=str(e))


@reports_router.post("/templates/init-default")
@log_api_request("init_default_templates")
@require_permission("report:create")
async def init_default_templates(
    current_user: User = Depends(get_current_active_user),
    db: Session = Depends(get_db)
):
    """初始化默认模板"""
    logger.info("初始化默认模板请求")
    
    try:
        report_service.template_manager.create_default_templates(db)
        
        return {"message": "默认模板初始化成功"}
        
    except Exception as e:
        logger.error(f"初始化默认模板失败: {str(e)}")
        raise HTTPException(status_code=500, detail=str(e))


@reports_router.get("/stats/summary")
@log_api_request("get_report_stats_summary")
@require_permission("report:view")
async def get_report_stats_summary(
    current_user: User = Depends(get_current_active_user),
    db: Session = Depends(get_db)
):
    """获取报告统计摘要"""
    logger.info("获取报告统计摘要请求")
    
    try:
        from sqlalchemy import func
        
        # 基础统计
        total_reports = db.query(models.report.Report).count()
        pending_reports = db.query(models.report.Report).filter(
            models.report.Report.status == ReportStatus.PENDING
        ).count()
        generating_reports = db.query(models.report.Report).filter(
            models.report.Report.status == ReportStatus.GENERATING
        ).count()
        completed_reports = db.query(models.report.Report).filter(
            models.report.Report.status == ReportStatus.COMPLETED
        ).count()
        failed_reports = db.query(models.report.Report).filter(
            models.report.Report.status == ReportStatus.FAILED
        ).count()
        
        # 今日统计
        today = datetime.now().date()
        today_reports = db.query(models.report.Report).filter(
            func.date(models.report.Report.created_at) == today
        ).count()
        
        # 成功率
        success_rate = 0
        if completed_reports + failed_reports > 0:
            success_rate = completed_reports / (completed_reports + failed_reports) * 100
        
        return {
            "total_reports": total_reports,
            "pending_reports": pending_reports,
            "generating_reports": generating_reports,
            "completed_reports": completed_reports,
            "failed_reports": failed_reports,
            "today_reports": today_reports,
            "success_rate": round(success_rate, 2)
        }
        
    except Exception as e:
        logger.error(f"获取报告统计摘要失败: {str(e)}")
        raise HTTPException(status_code=500, detail=str(e))


# AI智能报告生成接口
@reports_router.post("/generate/daily")
@log_api_request("generate_daily_report")
@require_permission("reports:generate")
async def generate_daily_report(
    request: DailyReportRequest,
    background_tasks: BackgroundTasks,
    current_user: User = Depends(get_current_active_user),
    db: Session = Depends(get_db)
):
    """生成AI智能日报"""
    logger.info("生成AI智能日报请求")
    
    try:
        # 确定报告日期
        report_date = request.report_date or datetime.now().date()
        
        # 创建报告记录
        report = models.report.Report(
            title=f"AI智能信访分析日报 - {report_date.strftime('%Y年%m月%d日')}",
            report_type=ReportType.DAILY,
            status=ReportStatus.GENERATING,
            created_by=current_user.id,
            report_date=report_date,
            config={"type": "ai_daily", "date": report_date.isoformat()}
        )
        
        db.add(report)
        db.commit()
        db.refresh(report)
        
        # 后台生成报告
        background_tasks.add_task(
            _generate_ai_daily_report_background,
            db, report.id, report_date, current_user.id
        )
        
        return {
            "success": True,
            "message": "AI智能日报生成任务已启动",
            "report_id": report.id,
            "status": "generating"
        }
        
    except Exception as e:
        logger.error(f"生成AI智能日报失败: {str(e)}")
        raise HTTPException(status_code=500, detail=str(e))


@reports_router.post("/generate/weekly")
@log_api_request("generate_weekly_report")
@require_permission("reports:generate")
async def generate_weekly_report(
    request: WeeklyReportRequest,
    background_tasks: BackgroundTasks,
    current_user: User = Depends(get_current_active_user),
    db: Session = Depends(get_db)
):
    """生成AI智能周报"""
    logger.info("生成AI智能周报请求")
    
    try:
        # 确定周开始日期
        if request.week_start:
            week_start = request.week_start
        else:
            # 默认为本周一
            today = datetime.now().date()
            week_start = today - timedelta(days=today.weekday())
        
        week_end = week_start + timedelta(days=7)
        
        # 创建报告记录
        report = models.report.Report(
            title=f"AI智能信访分析周报 - {week_start.strftime('%Y年%m月%d日')}至{week_end.strftime('%Y年%m月%d日')}",
            report_type=ReportType.WEEKLY,
            status=ReportStatus.GENERATING,
            created_by=current_user.id,
            report_date=week_start,
            config={"type": "ai_weekly", "week_start": week_start.isoformat()}
        )
        
        db.add(report)
        db.commit()
        db.refresh(report)
        
        # 后台生成报告
        background_tasks.add_task(
            _generate_ai_weekly_report_background,
            db, report.id, week_start, current_user.id
        )
        
        return {
            "success": True,
            "message": "AI智能周报生成任务已启动",
            "report_id": report.id,
            "status": "generating"
        }
        
    except Exception as e:
        logger.error(f"生成AI智能周报失败: {str(e)}")
        raise HTTPException(status_code=500, detail=str(e))


@reports_router.post("/generate/monthly")
@log_api_request("generate_monthly_report")
@require_permission("reports:generate")
async def generate_monthly_report(
    request: MonthlyReportRequest,
    background_tasks: BackgroundTasks,
    current_user: User = Depends(get_current_active_user),
    db: Session = Depends(get_db)
):
    """生成AI智能月报"""
    logger.info("生成AI智能月报请求")
    
    try:
        # 确定年份和月份
        now = datetime.now()
        year = request.year or now.year
        month = request.month or now.month
        
        # 创建报告记录
        report = models.report.Report(
            title=f"AI智能信访分析月报 - {year}年{month}月",
            report_type=ReportType.MONTHLY,
            status=ReportStatus.GENERATING,
            created_by=current_user.id,
            report_date=datetime(year, month, 1),
            config={"type": "ai_monthly", "year": year, "month": month}
        )
        
        db.add(report)
        db.commit()
        db.refresh(report)
        
        # 后台生成报告
        background_tasks.add_task(
            _generate_ai_monthly_report_background,
            db, report.id, year, month, current_user.id
        )
        
        return {
            "success": True,
            "message": "AI智能月报生成任务已启动",
            "report_id": report.id,
            "status": "generating"
        }
        
    except Exception as e:
        logger.error(f"生成AI智能月报失败: {str(e)}")
        raise HTTPException(status_code=500, detail=str(e))


@reports_router.post("/generate/custom")
@log_api_request("generate_custom_report")
@require_permission("reports:generate")
async def generate_custom_report(
    request: CustomReportRequest,
    background_tasks: BackgroundTasks,
    current_user: User = Depends(get_current_active_user),
    db: Session = Depends(get_db)
):
    """生成AI智能自定义报告"""
    logger.info("生成AI智能自定义报告请求")
    
    try:
        # 验证日期范围
        if request.start_date >= request.end_date:
            raise HTTPException(status_code=400, detail="开始日期必须早于结束日期")
        
        # 限制时间范围
        max_days = 365  # 最多一年
        if (request.end_date - request.start_date).days > max_days:
            raise HTTPException(status_code=400, detail=f"时间范围不能超过{max_days}天")
        
        # 创建报告记录
        report = models.report.Report(
            title=request.title,
            report_type=ReportType.CUSTOM,
            status=ReportStatus.GENERATING,
            created_by=current_user.id,
            report_date=request.start_date,
            config={
                "type": "ai_custom",
                "title": request.title,
                "start_date": request.start_date.isoformat(),
                "end_date": request.end_date.isoformat(),
                "sections": request.sections,
                "analysis_config": request.analysis_config
            }
        )
        
        db.add(report)
        db.commit()
        db.refresh(report)
        
        # 后台生成报告
        background_tasks.add_task(
            _generate_ai_custom_report_background,
            db, report.id, request, current_user.id
        )
        
        return {
            "success": True,
            "message": "AI智能自定义报告生成任务已启动",
            "report_id": report.id,
            "status": "generating"
        }
        
    except HTTPException:
        raise
    except Exception as e:
        logger.error(f"生成AI智能自定义报告失败: {str(e)}")
        raise HTTPException(status_code=500, detail=str(e))


@reports_router.get("/{report_id}/ai-content")
@log_api_request("get_ai_report_content")
@require_permission("reports:view")
async def get_ai_report_content(
    report_id: int,
    current_user: User = Depends(get_current_active_user),
    db: Session = Depends(get_db)
):
    """获取AI报告内容"""
    logger.info(f"获取AI报告内容请求: {report_id}")
    
    try:
        report = db.query(models.report.Report).filter(models.report.Report.id == report_id).first()
        
        if not report:
            raise HTTPException(status_code=404, detail="报告不存在")
        
        if not report.config.get("type", "").startswith("ai_"):
            raise HTTPException(status_code=400, detail="此报告不是AI生成的报告")
        
        if report.status != ReportStatus.COMPLETED:
            return {
                "status": report.status,
                "message": "报告尚未生成完成"
            }
        
        return {
            "report_id": report.id,
            "title": report.title,
            "content": report.content,
            "data": report.data,
            "generated_at": report.generated_at.isoformat() if report.generated_at else None
        }
        
    except HTTPException:
        raise
    except Exception as e:
        logger.error(f"获取AI报告内容失败: {str(e)}")
        raise HTTPException(status_code=500, detail=str(e))


@reports_router.get("/ai-templates")
@log_api_request("list_ai_report_templates")
@require_permission("reports:view")
async def list_ai_report_templates(
    current_user: User = Depends(get_current_active_user)
):
    """获取AI报告模板列表"""
    logger.info("获取AI报告模板列表请求")
    
    try:
        templates = [
            {
                "id": "ai_daily_standard",
                "name": "AI标准日报",
                "description": "利用AI技术生成的标准日报，包含当日数据统计、趋势分析、地理分布等内容",
                "report_type": "daily",
                "sections": ["overview", "statistics", "trends", "geo_analysis", "key_issues"],
                "config": {
                    "include_charts": True,
                    "include_recommendations": True,
                    "ai_analysis_depth": "standard"
                }
            },
            {
                "id": "ai_weekly_comprehensive",
                "name": "AI综合周报",
                "description": "AI生成的综合周报，包含周度数据统计、趋势变化、对比分析等内容",
                "report_type": "weekly",
                "sections": ["overview", "statistics", "trends", "comparison", "geo_analysis", "recommendations"],
                "config": {
                    "include_charts": True,
                    "include_recommendations": True,
                    "include_weekly_comparison": True,
                    "ai_analysis_depth": "comprehensive"
                }
            },
            {
                "id": "ai_monthly_strategic",
                "name": "AI战略月报",
                "description": "AI生成的战略级月报，包含月度数据统计、趋势分析、分类分析等内容",
                "report_type": "monthly",
                "sections": ["overview", "statistics", "trends", "category_analysis", "regional_analysis", "strategic_recommendations"],
                "config": {
                    "include_charts": True,
                    "include_recommendations": True,
                    "include_monthly_summary": True,
                    "ai_analysis_depth": "strategic"
                }
            },
            {
                "id": "ai_custom_analysis",
                "name": "AI专项分析报告",
                "description": "AI生成的专项分析报告，针对特定问题进行深入分析",
                "report_type": "custom",
                "sections": ["overview", "key_issues", "detailed_analysis", "root_cause_analysis", "recommendations"],
                "config": {
                    "include_charts": True,
                    "include_recommendations": True,
                    "focus_on_key_issues": True,
                    "ai_analysis_depth": "deep"
                }
            },
            {
                "id": "ai_predictive_analysis",
                "name": "AI预测分析报告",
                "description": "AI生成的预测分析报告，基于历史数据进行趋势预测和风险预警",
                "report_type": "custom",
                "sections": ["historical_analysis", "trend_prediction", "risk_assessment", "early_warning", "recommendations"],
                "config": {
                    "include_charts": True,
                    "include_predictions": True,
                    "include_risk_assessment": True,
                    "ai_analysis_depth": "predictive"
                }
            }
        ]
        
        return {
            "templates": templates,
            "total": len(templates)
        }
        
    except Exception as e:
        logger.error(f"获取AI报告模板列表失败: {str(e)}")
        raise HTTPException(status_code=500, detail=str(e))


# 后台任务函数
async def _generate_ai_daily_report_background(
    db: Session, 
    report_id: int, 
    report_date: datetime,
    user_id: int
):
    """后台生成AI日报"""
    try:
        # 生成报告数据
        report_data = await report_generation_service.generate_daily_report(
            db, report_date, user_id
        )
        
        # 更新报告记录
        report = db.query(models.report.Report).filter(models.report.Report.id == report_id).first()
        if report:
            report.status = ReportStatus.COMPLETED
            report.content = report_data["content"]
            report.data = report_data
            report.generated_at = datetime.now()
            db.commit()
            
        logger.info(f"AI日报生成完成，报告ID: {report_id}")
        
    except Exception as e:
        logger.error(f"后台生成AI日报失败: {str(e)}")
        
        # 更新报告状态为失败
        report = db.query(models.report.Report).filter(models.report.Report.id == report_id).first()
        if report:
            report.status = ReportStatus.FAILED
            report.error_message = str(e)
            db.commit()


async def _generate_ai_weekly_report_background(
    db: Session, 
    report_id: int, 
    week_start: datetime,
    user_id: int
):
    """后台生成AI周报"""
    try:
        # 生成报告数据
        report_data = await report_generation_service.generate_weekly_report(
            db, week_start, user_id
        )
        
        # 更新报告记录
        report = db.query(models.report.Report).filter(models.report.Report.id == report_id).first()
        if report:
            report.status = ReportStatus.COMPLETED
            report.content = report_data["content"]
            report.data = report_data
            report.generated_at = datetime.now()
            db.commit()
            
        logger.info(f"AI周报生成完成，报告ID: {report_id}")
        
    except Exception as e:
        logger.error(f"后台生成AI周报失败: {str(e)}")
        
        # 更新报告状态为失败
        report = db.query(models.report.Report).filter(models.report.Report.id == report_id).first()
        if report:
            report.status = ReportStatus.FAILED
            report.error_message = str(e)
            db.commit()


async def _generate_ai_monthly_report_background(
    db: Session, 
    report_id: int, 
    year: int,
    month: int,
    user_id: int
):
    """后台生成AI月报"""
    try:
        # 生成报告数据
        report_data = await report_generation_service.generate_monthly_report(
            db, year, month, user_id
        )
        
        # 更新报告记录
        report = db.query(models.report.Report).filter(models.report.Report.id == report_id).first()
        if report:
            report.status = ReportStatus.COMPLETED
            report.content = report_data["content"]
            report.data = report_data
            report.generated_at = datetime.now()
            db.commit()
            
        logger.info(f"AI月报生成完成，报告ID: {report_id}")
        
    except Exception as e:
        logger.error(f"后台生成AI月报失败: {str(e)}")
        
        # 更新报告状态为失败
        report = db.query(models.report.Report).filter(models.report.Report.id == report_id).first()
        if report:
            report.status = ReportStatus.FAILED
            report.error_message = str(e)
            db.commit()


async def _generate_ai_custom_report_background(
    db: Session, 
    report_id: int, 
    request: CustomReportRequest,
    user_id: int
):
    """后台生成AI自定义报告"""
    try:
        # 生成报告数据
        report_data = await report_generation_service.generate_custom_report(
            db, request.start_date, request.end_date, 
            {
                "title": request.title,
                "sections": request.sections,
                **(request.analysis_config or {})
            },
            user_id
        )
        
        # 更新报告记录
        report = db.query(models.report.Report).filter(models.report.Report.id == report_id).first()
        if report:
            report.status = ReportStatus.COMPLETED
            report.content = report_data["content"]
            report.data = report_data
            report.generated_at = datetime.now()
            db.commit()
            
        logger.info(f"AI自定义报告生成完成，报告ID: {report_id}")
        
    except Exception as e:
        logger.error(f"后台生成AI自定义报告失败: {str(e)}")
        
        # 更新报告状态为失败
        report = db.query(models.report.Report).filter(models.report.Report.id == report_id).first()
        if report:
            report.status = ReportStatus.FAILED
            report.error_message = str(e)
            db.commit()